package us.icitap.cm.ui.shared;

import us.icitap.cm.listeners.ReturnObjectListener;
import us.icitap.cm.ui.custom.CustVerticalLayout;
import us.icitap.cm.ui.custom.SearchAddressComponent;

import com.google.code.geocoder.model.GeocoderResult;
import com.google.code.geocoder.model.LatLng;
import com.vaadin.tapio.googlemaps.GoogleMap;
import com.vaadin.tapio.googlemaps.client.LatLon;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class MapComponent extends VerticalLayout {
	
	private GoogleMap googleMap;
		
	public MapComponent(String width, boolean withGeocoder, GoogleMap googleMap){
		setHeight("100%");
		setWidth(width);
		this.googleMap = googleMap;
		
		googleMap.setSizeFull();
		googleMap.setMinZoom(0.0);
		googleMap.setMaxZoom(21.0);
			
		CustVerticalLayout ml = new CustVerticalLayout();
		ml.setHeight("500px");
		ml.addComponentAsFirst(googleMap);
		
		if(withGeocoder)
			addGeocoder();
		addComponent(ml);
	}
	
	private void intiMap(){

	}
	
	private void addGeocoder(){
		SearchAddressComponent searchAdrComponent = new SearchAddressComponent(true, "100%");
		searchAdrComponent.addListener(new ReturnObjectListener() {
			@Override
			public <T> void returnObject(T result) {				
				GeocoderResult geoResult = (GeocoderResult) result;
				
				LatLon mapLoc = codePoint(geoResult.getGeometry().getLocation());
				googleMap.setCenter(mapLoc);
				googleMap.clearMarkers();
				googleMap.addMarker("Vend krimi", mapLoc, true, "");
				
				LatLon limitNE = codePoint(geoResult.getGeometry().getViewport().getNortheast());
				LatLon limitSE = codePoint(geoResult.getGeometry().getViewport().getSouthwest());
				
				googleMap.setVisibleAreaBoundLimits(limitNE, limitSE);
			}
			
		});
		addComponentAsFirst(searchAdrComponent);
	}
	
	private LatLon codePoint(LatLng geocodePoint){
		return new LatLon(geocodePoint.getLat().doubleValue(), geocodePoint.getLng().doubleValue());
	}

}
